/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.skatiger.jrove.tag;

import org.skatiger.jrove.JroveContext;
import org.skatiger.jrove.MetaRuleset;
import org.skatiger.jrove.Metadata;
import org.skatiger.jrove.TagConfig;
import org.skatiger.jrove.TagHandler;
import org.skatiger.jrove.util.AssertUtil;

public abstract class MetaTagHandler extends TagHandler {

	private Class<?> lastType = Object.class;

	private Metadata mapper;

	public MetaTagHandler(TagConfig config) {
		super(config);
	}

	/**
	 * Extend this method in order to add your own rules.
	 * 
	 * @param type
	 * @return
	 */
	protected MetaRuleset createMetaRuleset(Class<?> type) {
		AssertUtil.notNull(type);
		return new MetaRulesetImpl(this.tag, type);
	}

	/**
	 * Invoking/extending this method will cause the results of the created
	 * MetaRuleset to auto-wire state to the passed instance.
	 * 
	 * @param ctx
	 * @param instance
	 */
	protected void setAttributes(JroveContext ctx, Object instance) {
		if (instance != null) {
			Class<?> type = instance.getClass();
			if (mapper == null || !this.lastType.equals(type)) {
				this.lastType = type;
				MetaRuleset ruleset = this.createMetaRuleset(type);
				this.mapper = ruleset.finish();
			}
			this.mapper.applyMetadata(ctx, instance);
		}
	}
}
